var request = require('request');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var HashMap = require('hashmap');
var map = new HashMap();

app.get('/logout', function (req, res) {
    var userid = req.query.uid;
    console.log('logout,userid=' + userid);
    res.send({ result: 0 });
});

app.get('/login', function (req, res) {
    var username = req.query.username;
    var password = req.query.password;
    console.log('login,username=' + username + ',password=' + password);
    var result;
    if (username == 'root' && password == 'pass') {
        result = { result: 0, userid: 1 };
    } else {
        result = { result: 1, userid: -1 };
    }
    res.send(result);
});

app.get('/update', function (req, res) {
    var _userid = req.query.userid;
    console.log(_userid);
    if (_userid > 0) {
        var _userlist = req.query.userlist;
        map.set('list-' + _userid, _userlist);
        res.send({ result: 0 });
    } else {
        res.send({ result: 1 });
    }
});

app.get('/list', function (req, res) {
    var _userid = req.query.userid;
    //print json
    if (_userid > 0) {
        var _userlist = (map.get("list-" + _userid) || "[]");
        res.send({ result: 0, list: JSON.parse(_userlist) });
    } else {
        res.send({ result: 1 });
    }
});

//for websocket
io.on('connection', function (socket) {
    console.log('on connection' + socket);
    socket.on('login', function (data) {
        var userid = data.userid;
        console.log(data.userid);
        map.set('user-' + userid, socket);
    });

    socket.on('status', function (data) {
        var _userid = data.userid;
        if (_userid > 0) {
            console.log(data.result);
        }
    });
});

app.get('/play', function (req, res) {
    var _userid = req.query.userid;
    if (_userid > 0) {
        var _url = req.query.url;
        //print json
        var socket = map.get('user-' + _userid);
        socket.emit('play', { url: _url });
        var _result = { result: 0 };
        res.send(_result);
    } else {
        res.send({ result: 1 });
    }
});

app.get('/pause', function (req, res) {
    var _userid = req.query.userid;
    if (_userid > 0) {
        var _url = req.query.url;
        //print json
        var socket = map.get('user-' + _userid);
        socket.emit('pause', { url: _url });
        res.send({ result: 0 });
    } else {
        res.send({ result: 1 });
    }
});

server.listen(3000, function () {
    var port = server.address().port;
    console.log('listening at port:%s', port);
});
